package com.bluedot.pojo.pack;

import java.io.*;

/**
 * 文件分封装类，封装的是二进制数组和文件名称
 * @author QiYU
 */
public class FileResponse {

    private final byte[] fileBytes;
    private String fileName;

    public FileResponse(String fileName, InputStream in) throws IOException {
        if (in == null) {
            throw new NullPointerException("输入流为空");
        }
        // 将InputStream 变为 byte[] 数组
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        in.close();
        this.fileName = fileName;
        fileBytes = output.toByteArray();
    }


    public FileResponse(File file) throws IOException {
        this(file.getName(), new FileInputStream(file));
        if (!file.isFile()) {
            throw new RuntimeException(file + " 不是文件，而是文件夹");
        }
    }

    public FileResponse(String fileName, byte[] bytes) {
        this.fileName = fileName;
        this.fileBytes = bytes;
    }

    public FileResponse(String fileName, ByteArrayOutputStream os) {
        this.fileName = fileName;
        fileBytes = os.toByteArray();
    }


    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public byte[] getFileBytes() {
        return fileBytes;
    }
}
